﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Data;
using System.IO;

using System.Web.UI.WebControls;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.UserControls;
using Microsoft.VisualBasic.FileIO;



namespace DotNetNuke.Modules.UserDefinedTable
{


  public partial class ImportCSV : PortalModuleBase
  {

    private int ModuleId;




    public ImportCSV()
    {
      //base.Load += new EventHandler(this.Page_Load);
      this.ModuleId = -1;
    }



    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);
      //base.Load += new EventHandler(this.Page_Load);

      cmdCancel.Click += new EventHandler(cmdCancel_Click);
      cmdImport.Click += new EventHandler(cmdImport_Click);
      cboFolders.SelectedIndexChanged +=new EventHandler(cboFolders_SelectedIndexChanged);

    }



    //protected void Page_Load(object sender, EventArgs evt)
    protected override void OnLoad(EventArgs evt)
    {
      base.OnLoad(evt);

      try
      {
        if (this.Request.QueryString["moduleid"] != null)
          this.ModuleId = int.Parse(this.Request.QueryString["moduleid"]);
        
        if (!this.Page.IsPostBack)
        {
          this.cboFolders.Items.Insert(0, new ListItem(string.Format("<{0}>", DotNetNuke.Services.Localization.Localization.GetString("None_Specified")), "-"));
          ArrayList list = FileSystemUtils.GetFoldersByUser(this.PortalId, false, false, "READ, WRITE");

          ListItem item;

          foreach(FolderInfo current in list)
          {
            item = new ListItem();
            if (current.FolderPath == Null.NullString)
              item.Text = DotNetNuke.Services.Localization.Localization.GetString("Root", this.LocalResourceFile);

            else
              item.Text = current.FolderPath;

            item.Value = current.FolderPath;
            this.cboFolders.Items.Add(item);
          }
        }
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);

      }
    }




    private void cboFolders_SelectedIndexChanged(object sender, EventArgs evt)
    {
      this.cboFiles.Items.Clear();
      if (this.cboFolders.SelectedIndex != 0)
      {
        ModuleController controller = new ModuleController();
        if (controller.GetModule(this.ModuleId, this.TabId, false) != null)
        {
          IEnumerator enumerator = null;
          ArrayList list = DotNetNuke.Common.Globals.GetFileList(this.PortalId, "csv", false, this.cboFolders.SelectedItem.Value);
          try
          {
            enumerator = list.GetEnumerator();
            while (enumerator.MoveNext())
            {
              FileItem current = (FileItem)enumerator.Current;
              this.cboFiles.Items.Add(new ListItem(current.Text, current.Text));
            }
          }
          finally
          {
            if (enumerator is IDisposable)
              (enumerator as IDisposable).Dispose();
            
          }
        }
      }
    }




    private void cmdCancel_Click(object sender, EventArgs evt)
    {
      try
      {
        this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);

      }
    }




    private void cmdImport_Click(object sender, EventArgs evt)
    {
      try
      {
        if (this.cboFiles.SelectedItem != null)
        {
          ModuleController controller = new ModuleController();
          if (controller.GetModule(this.ModuleId, this.TabId, false) != null)
          {
            string message = this.ImportModule(this.ModuleId, this.cboFiles.SelectedItem.Value, this.cboFolders.SelectedItem.Value, this.rblDelimiter.SelectedValue);

            if (message == "")
              this.Response.Redirect(DotNetNuke.Common.Globals.NavigateURL(), true);
            
            else
              Skin.AddModuleMessage((PortalModuleBase)this, message, ModuleMessage.ModuleMessageType.RedError);
            
          }
        }
        else
        {
          Skin.AddModuleMessage((PortalModuleBase)this, "Please specify the file to import", ModuleMessage.ModuleMessageType.RedError);
        }
      }
      catch (Exception e)
      {

        Exception exc = e;
        DotNetNuke.Services.Exceptions.Exceptions.ProcessModuleLoadException((PortalModuleBase)this, exc);

      }
    }





    private static DataSet CreateFields(string[] columns, UserDefinedTableController UDTController)
    {
      UDTController.ResetModule();
      UDTController.GetFieldsTable();

      foreach (string str in columns)
        UDTController.AddField(str);
      
      return UDTController.GetRow(-1, false);
    }

    private DataRow FillRow(string[] data, DataRow row, int start)
    {
      int num2 = data.Length - 1;

      for (int i = 0; i <= num2; i++)
        row[(i + start) + 1] = data[i];
      
      return row;
    }





    private string ImportModule(int ModuleId, string FileName, string Folder, string Delimiter)
    {
      string str2 = "";
      ModuleController controller = new ModuleController();
      ModuleInfo info = controller.GetModule(ModuleId, this.TabId, false);
      if ((Path.GetExtension(FileName).ToUpper() == ".CSV") && (info != null))
      {
        UserDefinedTableController uDTController = new UserDefinedTableController(ModuleId, this.TabId, this.UserInfo);
        using (TextFieldParser parser = new TextFieldParser(this.PortalSettings.HomeDirectoryMapPath + Folder + FileName))
        {
          parser.TextFieldType = FieldType.Delimited;
          parser.SetDelimiters(new string[] { Delimiter });
          DataSet ds = null;
          DataTable table = null;
          string str5 = null;
          string str4 = null;
          string str7 = null;
          string str6 = null;
          int count = DataType.SystemDataTypes().Count;
          try
          {
            while (!parser.EndOfData)
            {
              string[] columns = parser.ReadFields();
              if (table == null)
              {
                ds = CreateFields(columns, uDTController);
                table = ds.Tables[DataSetTableName.Data];
                str5 = uDTController.ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_ChangedBy);
                str4 = uDTController.ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_ChangedAt);
                str7 = uDTController.ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_CreatedBy);
                str6 = uDTController.ColumnNameByDataType(ds, DataTypeNames.UDT_DataType_CreatedAt);
              }
              else
              {
                string str8 = DateTime.Now.ToString("s");
                DataRow row = table.NewRow();
                row[DataTableColumn.RowId] = -1;
                row[str5] = this.UserInfo.Username;
                row[str7] = this.UserInfo.Username;
                row[str4] = str8;
                row[str6] = str8;
                table.Rows.Add(this.FillRow(columns, row, count));
              }
            }
            if (ds != null)
            {
              int num3 = table.Rows.Count - 1;

              for (int i = 0; i <= num3; i++)
                uDTController.UpdateRow(ds, i, true);
              
              controller.UpdateModuleSetting(ModuleId, SettingName.ListOrForm, "List");
            }
            return str2;
          }
          catch (Exception e)
          {

            Exception exception = e;
            str2 = string.Format(DotNetNuke.Services.Localization.Localization.GetString("importError", this.LocalResourceFile), exception.Message);

          }
        }
      }
      return str2;
    }





  }

}

